<template>
  <div>
    <!-- 三方融资查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhFinanceQuery"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :cellstyles="cellstyles"
        :onSyncTableData="syncTableData"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" :disabled="withdrawHandledisabled" :click="withdrawHandle">撤回</multiuse-button>
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
          <multiuse-button size="small" type="primary" :disabled="isDisabled" @click="printHandle">批量打印</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <Drawer :visible.sync="visible" :title="drawerTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SonModel :type="handleType" :rowData="formData" @close="emitCloseHandler1" />
    </Drawer>

    <!-- 经销商查询 -->
    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>

    <!-- 批量打印 -->
    <div v-if="isPrint && appId == 'beijing'">
      <BasePrint ref="printPick" :data="printData" template="Finance/beijingFinancetpl" />
    </div>

    <div v-else-if="isPrint && appId == 'arcfox'">
      <BasePrint ref="printPick" :data="printData" template="Finance/arcfoxFinancetpl" />
    </div>
  </div>
</template>
<script>
import moment from 'moment';
import { getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
import { queryList, exportExcel, printStatus, exporturl, withdrawStatus } from '@/api/omFinance/FinanceManage/FinanceQuery';
import { exportExcelFile } from '@/utils/index';
import SonModel from './SonModel';
import OwnerSearch from '../OwnerSearch';

export default {
  name: 'FinanceQuery',
  mixins: [dictionary],

  components: {
    SonModel,
    OwnerSearch,
  },
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };

    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {
        xhrAbort: true,
      },
      formData: {},
      printData: {},
      cellstyles: [],
      handleData: [],
      isDisabled: true,
      withdrawHandledisabled: true,
      visible: false,
      appId: getAppId(),
      isDealer: false,
      isPrint: false,
      exportLoading: false,
      handleType: '',
      drawerTitle: '',
    };
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    syncTableData(data) {
      if (!data.length) return;
      data.forEach((x) => {
        if (x.isRiskDealer == 10041001) {
          this.cellstyles.push({ row: x, dataIndex: 'isRiskDealer', styles: { backgroundColor: 'red' } });
        }
        if (x.overdueQuantity > 0) {
          this.cellstyles.push({ row: x, dataIndex: 'overdueQuantity', styles: { backgroundColor: 'red' } });
        }
        if (x.stockFactor > x.stockFactorLimit) {
          this.cellstyles.push({ row: x, dataIndex: 'stockFactor', styles: { backgroundColor: 'red' } });
        }
      });
    },
    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      let dealerCodes = [];
      let dealerNames = [];
      data.map((x) => {
        dealerCodes.push(x.dealerCode);
        dealerNames.push(x.dealerName);
      });
      this.topFilterList.find((x) => x.fieldName == 'ownerCode').initialValue = dealerCodes.toString();
    },
    changeHandle(params) {
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    emitCloseHandler1(val) {
      this.visible = val;
    },
    detailHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    showHandler() {
      this.drawerTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    selectChangeHandle(rows) {
      if (rows.length > 0) {
        this.isDisabled = false;
        this.withdrawHandledisabled = false;
        this.handleData = rows;
        if (rows.length > 0) {
          rows.map((x) => {
            x.payeeNew = this.createDictText(x.payee, '6031');
            x.applyDateNew = moment(x.applyDate).format('YYYY年MM月DD日');
          });
        }

        this.printData = { data: rows };
        console.log(this.printData, '---奥利给---');
        return;
      }
      this.isDisabled = true;
    },
    // 批量打印
    async printHandle() {
      this.isPrint = true;
      let Ids = [];
      this.handleData.map((x) => {
        Ids.push(x.id);
      });
      const res = await printStatus({ ids: Ids });
      if (res.resultCode == 200) {
        this.$nextTick(() => {
          this.$refs.printPick.EXCUTE_PRINT();
        });
      }
    },
    //撤回-
    async withdrawHandle() {
      let Ids = [];
      this.handleData.map((x) => {
        Ids.push(x.id);
      });
      var res = await withdrawStatus({ ids: Ids });
      if (res.data == true) {
          // this.fetchParams = Object.assign({}, this.fetchParams, {xhrAbort: false});
          this.fetchParams = { ...this.fetchParams };
      }
    },
    // 导出
    async exportHandle() {
      let json = Object.assign({}, { CODE: 'CODE_0000089' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;

      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '三方融资查询');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'ownerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          },
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '申请单号',
          fieldName: 'applyNo',
          placeholder: '请选择',
        },
        {
          type: 'SELECT',
          label: '审批状态',
          fieldName: 'businessStatus',
          placeholder: '请选择',
          itemList: [
            { text: '待大客户部部长审批', value: 60301002 },
            { text: '待事业部部长审批', value: 60301003 },
            { text: '待总部金融科审批', value: 60301004 },
            { text: '审批通过', value: 60301005 },
            { text: '审批驳回', value: 60301006 },
          ],
        },
        {
          type: 'INPUT',
          label: '银行名称',
          fieldName: 'bankName',
          placeholder: '请选择',
        },
        {
          type: 'RANGE_DATE',
          label: '申请日期',
          fieldName: 'startApplyDate|endApplyDate',
          dateType: 'exactdaterange',
          placeholder: '请选择',
        },
        {
          type: 'SELECT',
          label: '打印状态',
          fieldName: 'printStatus',
          placeholder: '请选择',
          itemList: this.createDictList('1004'),
        },
        {
          type: 'SELECT',
          label: '提车公司',
          fieldName: 'salesCompany',
          placeholder: '请选择',
          itemList: this.createDictList('2555'),
        },
        {
          type: 'SELECT',
          label: '申请类型',
          fieldName: 'applyType',
          placeholder: '请选择',
          itemList: this.createDictList('6073'),
        },
        {
          type: 'RANGE_DATE',
          label: '金融科审核时间',
          fieldName: 'startHeadCheckDate|endHeadCheckDate',
          dateType: 'datetimerange',
          placeholder: '请选择',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '审批状态',
          dataIndex: 'businessStatusName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '打印状态',
          dataIndex: 'printStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '申请单号',
          dataIndex: 'applyNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'ownerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '银行名称',
          dataIndex: 'bankName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '申请类型',
          dataIndex: 'applyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6073'),
          render: (props) => {
            return <span>{this.createDictText(props.row.applyType, '6073')}</span>;
          },
        },
        {
          title: '出票金额（万）',
          dataIndex: 'billAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
        },
        {
          title: '出票期限',
          dataIndex: 'billDeadlineName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '银行联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '银行联系电话',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          filterType: 'input',
        },

        {
          title: '金融科审核时间',
          dataIndex: 'headCheckDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'YYYY-MM-DD HH:mm:ss',
        },
        {
          title: '申请日期',
          dataIndex: 'applyDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'YYYY-MM-DD',
        },
        {
          title: '提车公司',
          dataIndex: 'salesCompanyName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '收款方',
          dataIndex: 'payee',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6031'),
          render: (props) => {
            return <span>{this.createDictText(props.row.payee, '6031')}</span>;
          },
        },
        {
          title: '本月已开票金额',
          dataIndex: 'invoiceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
        },
        {
          title: '上月终端',
          dataIndex: 'lastSalesQuantity',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '前三月平均终端',
          dataIndex: 'averageSalesQuantity',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '库存',
          dataIndex: 'stockQuantity',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '库存系数',
          dataIndex: 'stockFactor',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '库存系数上限',
          dataIndex: 'stockFactorLimit',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '目前库销比',
          dataIndex: 'stockSalesRatio',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '超期车台数',
          dataIndex: 'overdueQuantity',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '是否为风险关注店',
          dataIndex: 'isRiskDealer',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: (props) => {
            return <span>{this.createDictText(props.row.isRiskDealer, '1004')}</span>;
          },
        },
        {
          title: '移动比例',
          dataIndex: 'moveRatio',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '回款率',
          dataIndex: 'collectionRate',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '备注',
          dataIndex: 'applyRemark',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        // {
        //   title: '审批时间',
        //   dataIndex: 'headCheckDate',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'date-range'
        // },
        // {
        //   title: '审批意见',
        //   dataIndex: 'headCheckRemark',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // }
      ];
    },
  },
};
</script>
